<?php

namespace App\Models;

use App\Models\Traits\UsesUuid;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Voucher extends Model
{
    use HasFactory, UsesUuid;

    protected $guarded = [];

    public $incrementing = false;
//    public $hidden = ['id'];
    protected $keyType = 'string';
    protected $statuses = ['0' => '待激活', '1' => '可使用', '2' => '待兑换', '3' => '已兑换', '4' => '已失效'];
    protected $appends = ['statusTitle'];


    //获取当前代金券各种状态

    public function judge()
    {
        $isOvertime = (new Carbon)->diffInMinutes($this->overtime, true) < 0;


        $isExchange = $this->status == 3;
        //判断状态
        //1、失效时间、2、已经兑换过

        //不可交易条件>3
        if ($isOvertime) {
            return new Exception('代金券已失效');
        } else if ($isExchange) {
            return new Exception('代金券已兑换，不能重复兑换');
        }
        return true;
    }


    public function records()
    {
        return $this->hasMany(Record::class, 'voucher_id', 'uuid');
    }

    public function getStatusTitleAttribute()
    {
        return $this->statuses[$this->status];
    }


    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

